from ronglian_sms_sdk import SmsSDK
from flask import current_app
import json, redis

# 发送短信验证码
class RongTool():
    def __init__(self):
        accId = current_app.config.get('ACCOUNT_SID')
        accToken = current_app.config.get('AUTH_TOKEN')
        appId = current_app.config.get('APPID')
        self.sdk = SmsSDK(accId, accToken, appId)

        host = current_app.config.get('REDIS_HOST')
        port = current_app.config.get('REDIS_PORT')
        self.r = redis.Redis(host, port)

    def sms_code(self, mobile, sms_code):
        tid = current_app.config.get('TID')

        datas = (sms_code, 5)

        # 发送验证码
        ser = self.sdk.sendMessage(tid, mobile, datas)
        data = json.loads(ser)

        # 添加到数据库
        self.r.set(str(mobile), sms_code, ex=3600 * 5)

        if data['statusCode'] == '000000':
            return True
        return False


if __name__ == '__main__':
    from app import app
    with app.app_context():
        RongTool().sms_code('18095466934', '666')